#include<iostream>
#include<cstdlib>
#include<ctime>
#include<cstring>
#include<assert.h>
#include<cv.h>
#include<highgui.h>
#define K_MAX 1024
#define D 3

int main(int argc, char* argv[])
{
	srand(time(0));
	if(argc < 3 )
	{
		printf("Command error: ./compress [file_to_be_compressed] [K] ([times])?\n");
		return -1;
	}

	int K;

	if( sscanf(argv[2],"%d", &K) !=1 )
	{
		printf("Second parameter K must be a number\n");
		return -1;
	}
	if( K > K_MAX )
	{
		printf("K must no be bigger than %d", K_MAX);
		return -1;
	}
	
	int T ; // used to define more video processing
	if(argc != 4 ||   sscanf(argv[3],"%d", &T) !=1 )
	{
		T =1;
	}

	cvNamedWindow("Compression",CV_WINDOW_AUTOSIZE);
	cvNamedWindow("Original",CV_WINDOW_AUTOSIZE);
	CvCapture* capture = cvCreateFileCapture(argv[1]);
	
	if( !capture )
	{
		printf( "\"%s\": File not found\n",argv[1]);
		return -1;
	}


	
	int R = 0;
	while( 1LL<<(24-3*R) > K  )
	{
		++R;
	}

	printf("R: %d\n",R);

	IplImage* frame;
	
	int iter = 0;
	bool fst = 1;

	// compress frame
	while(1)
	{
		// global variables
		++iter; 
		///

		frame = cvQueryFrame(capture);
		if(!frame)
			break;
		
		cvShowImage("Original",frame);
		
		//find parameters
		int n = frame->height ;// rows
		int m = frame->width;//columns

		int ch = frame->nChannels;
		assert(ch == D);

		int co[D];
		for(int r=0, i=0;r<n;++r)
			for(int c=0;c<m;++c,++i)
			{
				//find color
				for(int j=0;j<ch;++j)
					co[j] = (unsigned char) frame->imageData[ch*(r*m+c)+j];
				
				for(int j=0;j<ch;++j)
					frame->imageData[ch*(r*m+c)+j] = (unsigned char)( (co[j] >> R) << R );
			}

		cvShowImage("Compression",frame);

		++iter;
		//printf("Iter : %d\n",iter);
		char c = cvWaitKey(33);
		if(c == 27)
			break;
		//printf("\n");
	}
	cvReleaseCapture(&capture);
	cvDestroyWindow("Compression");
	return 0;
}
